﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Game.Contract.Action;
using ZyGames.Framework.Game.Lang;
using ZyGames.Framework.Game.Service;
using System.Linq;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Script;
using ZyGames.DZPocker.Tools;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 创建房间
	/// </summary>
	public class Action10030 : BaseAction
	{
		private string _roomName = string.Empty;
		/// <summary>
		/// 盲注等级
		/// </summary>
		private int _bindLevel;
		/// <summary>
		/// 时长等级
		/// </summary>
		private int _timeLevel;
		private bool _isGripper;
		private bool _insurance;
		private int _vipType;
		private bool _canNotOnLooking;
		private int _normalScore;
		private int _cost;
		private int _currentCoin;
		private int _userID;
		private GameUser _currentGameUser = null;

		private int _tableId;
		private string _inviteNum;
		private int _coinNum;
		private bool _createResult;
		private string _errorLog;
		private string masterHeadIcon = string.Empty;
		//默认的一个房间号
		private int _gameRoom;

		private BindLevelCostsInfo bindCost;
		private TimeLevelCostsInfo timeCost;

		private int masterId;

		public Action10030(HttpGet actionGetter)
			: base((short)ActionType.DZCreateRoom, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetString("RoomName", ref _roomName) &&
				httpGet.GetInt("BindLevel", ref _bindLevel) &&
				httpGet.GetInt("TimeLevel", ref _timeLevel) &&
				httpGet.GetBool("IsGripper", ref _isGripper) &&
				httpGet.GetBool("Insurance", ref _insurance) &&
				httpGet.GetInt("VIP", ref _vipType) &&
				httpGet.GetBool("CanNotOnLooking", ref _canNotOnLooking) &&
				httpGet.GetInt("NormalScore", ref _normalScore) &&
				httpGet.GetInt("Cost", ref _cost) &&
				httpGet.GetInt("CurrentCoin", ref _currentCoin) &&
				httpGet.GetInt("UserID", ref _userID))
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		public override bool TakeAction()
		{
			try
			{
				_currentGameUser = GameTable.Current.GetUser(_userID);
				if(_currentGameUser.Property.TableIdList.Count >= 4)
				{
					Tool.WriteErrorLine("协议10030：玩家已经创建超过四桌了，不好在创建了");
					return false;
				}
				//强制重置玩家的座位跟Ready状态，不知道哪儿给赋值了
				//_currentGameUser.Property.ResetState();
				if (_currentGameUser == null)
				{
					ErrorCode = Language.Instance.ErrorCode;
					Tool.WriteErrorLine("协议10030：不存在当前玩家");
					return false;
				}
				var gameUserTotalCoin = _currentGameUser.GameCoin;
				//计算服务费
				//不允许旁观
				var _canNotOnLookingCost = ConfigEnvSet.GetInt("GameSetting.CanNotOnLookingCost", 2);
				//强制抓头费用
				var _gripperCost = ConfigEnvSet.GetInt("GameSetting.GripperCost", 2);

				bindCost = new ShareCacheStruct<BindLevelCostsInfo>().FindAll().Where(i => i.BindLevel == _bindLevel).FirstOrDefault();
				timeCost = new ShareCacheStruct<TimeLevelCostsInfo>().FindAll().Where(i => i.TimeLevel == _timeLevel).FirstOrDefault();

				int coinTotalCost = 0; //这里取消原来的最低消耗
				coinTotalCost += _isGripper ? _gripperCost : 0;
				coinTotalCost += _canNotOnLooking ? _canNotOnLookingCost : 0;
				if (_vipType != (int)VIPType.None)
				{
					if (_vipType == (int)VIPType.PerWinner)
						coinTotalCost += ConfigEnvSet.GetInt("GameSetting.VIPPerWinnerPersonCost", 5);
					else if (_vipType == (int)VIPType.PerRound)
						coinTotalCost += ConfigEnvSet.GetInt("GameSetting.VIPPerRondCost", 2);
				}
				//盲注消费
				if (bindCost != null)
					coinTotalCost += bindCost.LevelCost;
				else
				{
					_createResult = false;
					_errorLog = "当前不存在盲注等级";
					Tool.WriteErrorLine("当前不存在盲注等级");
					return false;
				}

				//保险消费
				if (_insurance)
				{
					coinTotalCost += bindCost.InsuranceCost;
				}
				int time = 0;
				//时长消费
				if (timeCost != null)
				{
					coinTotalCost += timeCost.TimeCosts;
					time = timeCost.TimeValue;
				}
				else
				{
					_createResult = false;
					_errorLog = "当期那不存在时长等级";
					Tool.WriteErrorLine("当期那不存在时长等级");
					return false;
				}
				if (coinTotalCost > gameUserTotalCoin)
				{
					_createResult = false;
					_errorLog = "金币不足,跳转到商城页面";
					return false;
				}
				else
				{
					_createResult = true;
					_errorLog = "";
					//修改玩家的属性值并且同步到数据库
					_currentGameUser.ModifyLocked(() =>
					{
						_currentGameUser.GameCoin -= coinTotalCost;
					});
					var gameRoom = GameRoom.Current;
					if (gameRoom == null)
					{
						_createResult = false;
						_errorLog = "GameRoom不存在";
						Tool.WriteErrorLine("GameRoom不存在");
						return false;
					}
					var roomInfo = gameRoom.GetRoom(ConfigEnvSet.GetInt("GameSetting.DefaultRoomID", 1001));
					if (roomInfo == null)
					{
						Tool.WriteErrorLine("房间不存在");
						_createResult = false;
						_errorLog = "房间不存在";
						return false;
					}

					TableData tableData = null;
					gameRoom.EnterRoomAndCreateTable(this._currentGameUser, roomInfo, out tableData);
					if (tableData == null)
					{
						_createResult = false;
						_errorLog = "创建房间失败";
						Tool.WriteErrorLine("创建房间失败");
						return false;
					}
					//获得桌子的号码和邀请码
					_tableId = tableData.TableId;
					_inviteNum = tableData.InviteNum.ToString();
					tableData.TableName = _roomName;
					tableData.BindLevelCost = bindCost;
					tableData.TimeLevelCost = timeCost;
					tableData.BindLevel = _bindLevel;
					tableData.TimeLevel = _timeLevel;
					tableData.CanNotOnLooking = _canNotOnLooking;
					tableData.Vip = _vipType;
					tableData.IsGripper = _isGripper;
					tableData.Insurance = _insurance;
					tableData.TotalTime = time;
					this._coinNum = _currentGameUser.GameCoin;

					//设置房主的状态为ready
					//_currentGameUser.Property.SetReadyState(_tableId, true);

					var chip = tableData.BindLevelCost.SmallBind * 2 * ConfigEnvSet.GetInt("GameSetting.ChipSetting", 100);
					if (tableData.Chip == 0)
						tableData.Chip = chip;
					//设置房主
					tableData.TableMaster = _currentGameUser;
					this.masterId = _currentGameUser.UserId;
					//this.masterHeadIcon = _currentGameUser.HeadIconBytes;
					//默认房主就是保险人
					if(_insurance)
					{
						tableData.InsureId = _currentGameUser.GetUserId();
					}
					return true;
				}
			}
			catch (Exception ex)
			{
				Tool.WriteErrorLine(string.Format("桌子{0}协议10030程序异常:",_tableId, ex.ToString()));
				return false;
			}
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(_tableId);
			this.PushIntoStack(_roomName);
			this.PushIntoStack(_inviteNum);
			this.PushIntoStack(_coinNum);
			this.PushIntoStack(_bindLevel);
			this.PushIntoStack(_timeLevel);
			this.PushIntoStack(_isGripper);
			this.PushIntoStack(_insurance);
			this.PushIntoStack(_vipType);
			this.PushIntoStack(_canNotOnLooking);
			this.PushIntoStack(_cost);
			this.PushIntoStack(_createResult);
			this.PushIntoStack(_errorLog);
			//this.PushIntoStack(masterHeadIcon);
			this.PushIntoStack(masterId);
		}
	}
}
